<template>
  <div class="box">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>超市综合管理系统登录</span>
      </div>
      <el-form label-width="80px" :model="user" :rules="rules" ref="loginForm">
        <el-form-item label="账号" prop="account">
          <el-input v-model="user.account"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="user.password"
            @keyup.enter.native="login"
          ></el-input>
        </el-form-item>
        <el-button type="primary" @click="login">登录</el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script>
// 导入ajax工具包
import { userLogin } from "@/api/user";

export default {
  data() {
    return {
      user: {
        account: "",
        password: "",
      },
      rules: {
        account: [{ required: true, message: "请输入账号", trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
    };
  },
  methods: {
    login() {
      // 需要对表单进行验证，通过之后，发送ajax，访问后台，通过返回的结果决定是否登录成功
      this.$refs.loginForm.validate((data) => {
        if (data) {
          // 发送ajax
          userLogin(this.user).then((resp) => {
            let respData = resp.data;
            console.log(respData);
            if (respData.code == 20000) {
              // 将用户的角色存储在本地
              localStorage.setItem(
                "loginUser",
                JSON.stringify(respData.data)
              );
              // localStorage.setItem(
              //   "emp",
              //   JSON.stringify(respData.data[0].role)
              // );
              localStorage.setItem(
                "account",
                JSON.stringify(respData.data.account)
              );
              // this.$store.commit("SET_LOGIN_USER", respData.data[0]);
              // 路由需要跳转，
              this.$router.push("/home");//登录成功跳转到home页面
            }
          });
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
.box {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background-image: url(../../assets/imgs/login-bg.png);
  background-repeat: no-repeat;
  background-position: center top;
  background-size: cover;
  .box-card {
    width: 400px;
    height: 280px;
    color: #0af;
    .el-button {
      width: 100%;
    }
  }
}
</style>
